package com.jyy.prefabricated.service;

import com.jyy.prefabricated.entity.SmsRecord;
import com.jyy.prefabricated.enums.BaseStatusEnum;
import com.jyy.prefabricated.exception.CustomException;
import com.jyy.prefabricated.mapper.SmsRecordMapper;
import com.jyy.prefabricated.mapper.SmsRecordMapper;
import com.jyy.prefabricated.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * @version 1.0.0
 * @author: zjj
 */

@Service
public class SmsRecordService {

    @Autowired
    private SmsRecordMapper smsRecordMapper;


    public Integer insert(SmsRecord smsRecord){
        smsRecord.setStatus(BaseStatusEnum.VALID.getValue());
        smsRecordMapper.insert(smsRecord);
        return smsRecord.getId();
    }


    public int update(SmsRecord smsRecord){
        if(smsRecord.getId() == null){
            throw new CustomException("参数id不能为空");
        }
        return smsRecordMapper.updateByPrimaryKeySelective(smsRecord);
    }


    public int delete(Integer id){
        return smsRecordMapper.deleteByPrimaryKey(id);
    }

    public SmsRecord selectById(Integer id){
        return smsRecordMapper.selectByPrimaryKey(id);
    }


    public SmsRecord selectLast(String tel){
        return smsRecordMapper.selectLast(tel);
    }

    public void checkCode(String tel, String code){
        SmsRecord smsRecord = selectLast(tel);
        if(smsRecord == null){
            throw new CustomException("验证码错误！");
        }
        if(!smsRecord.getStatus().equals(BaseStatusEnum.VALID.getValue())){
            throw new CustomException("验证码已失效！");
        }
        long minutes = DateUtils.pastMinutes(smsRecord.getCreateTime());
        if(minutes >= 10){
            throw new CustomException("验证码已失效！");
        }
        if(!smsRecord.getCode().equals(code)){
            throw new CustomException("验证码错误！");
        }
        smsRecord.setStatus(BaseStatusEnum.INVALID.getValue());
        update(smsRecord);
    }
}
